<template>
  <div class="account-config-edit">
    <div class="page-header">
      <div class="header-left">
        <h3>{{ isEdit ? '编辑' : '新建' }}账号配置</h3>
        <p>{{ accountName }} 的配置管理</p>
      </div>
      <div class="header-right">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSave">
          {{ saving ? '保存中...' : '保存' }}
        </el-button>
      </div>
    </div>

    <div class="edit-content">
      <el-row :gutter="20">
        <!-- 左侧表单 -->
        <el-col :span="16">
          <el-card class="form-card">
            <el-form
              ref="configFormRef"
              :model="configForm"
              :rules="configRules"
              label-width="120px"
              label-position="left">

              <!-- 基础信息 -->
              <div class="form-section">
                <h4>基础信息</h4>
                <el-form-item label="配置名称" prop="configName">
                  <el-input v-model="configForm.configName" placeholder="请输入配置名称" clearable />
                </el-form-item>

                <el-form-item label="项目名称" prop="projectName">
                  <el-input v-model="configForm.projectName" placeholder="请输入项目名称" clearable />
                </el-form-item>

                <el-form-item label="备注">
                  <el-input
                    v-model="configForm.remark"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入配置备注"
                    clearable />
                </el-form-item>
              </div>

              <!-- 资产配置 -->
              <div class="form-section">
                <h4>资产配置</h4>
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="基础资产" prop="baseAsset">
                      <el-input v-model="configForm.baseAsset" placeholder="如：ALPHA_387" clearable />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="报价资产" prop="quoteAsset">
                      <el-input v-model="configForm.quoteAsset" placeholder="如：USDT" clearable />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="区块链ID" prop="chainId">
                      <el-input-number
                        v-model="configForm.chainId"
                        :min="1"
                        placeholder="如：56"
                        style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="合约地址" prop="contractAddress">
                      <div class="input-with-button">
                        <el-input
                          v-model="configForm.contractAddress"
                          placeholder="0x..."
                          clearable
                          @input="handleContractAddressChange" />
                        <el-button
                          type="primary"
                          :loading="fetchingTokenInfo"
                          :disabled="!configForm.contractAddress || !/^0x[a-fA-F0-9]{40}$/.test(configForm.contractAddress)"
                          @click="fetchTokenInfo"
                          class="fetch-button">
                          获取信息
                        </el-button>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <!-- 交易配置 -->
              <div class="form-section">
                <h4>交易配置</h4>
                <el-row :gutter="16">
                  <el-col :span="12">
                    <el-form-item label="购买金额">
                      <el-input-number
                        v-model="configForm.buyAmount"
                        :min="0"
                        :precision="8"
                        placeholder="购买金额"
                        style="width: 100%" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="目标报价">
                      <el-input-number
                        v-model="configForm.targetBuyQuote"
                        :min="0"
                        :precision="8"
                        placeholder="目标购买报价"
                        style="width: 100%" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <!-- 代理配置 -->
              <div class="form-section">
                <h4>代理配置</h4>
                <el-form-item label="启用代理">
                  <el-switch v-model="configForm.proxyEnabled" />
                </el-form-item>

                <el-form-item v-if="configForm.proxyEnabled" label="代理设置">
                  <ProxyConfigEditor v-model="configForm.proxyConfig" />
                </el-form-item>
              </div>

              <!-- 通知配置 -->
              <div class="form-section">
                <h4>通知配置</h4>
                <el-form-item label="通知URL">
                  <el-input v-model="configForm.notifyUrl" placeholder="Webhook通知地址" clearable />
                </el-form-item>
              </div>

              <!-- 自定义配置 -->
              <div class="form-section">
                <h4>自定义配置</h4>
                <el-form-item label="高级配置">
                  <JsonEditor v-model="configForm.customConfig" :height="200" />
                </el-form-item>
              </div>
            </el-form>
          </el-card>
        </el-col>

        <!-- 右侧预览 -->
        <el-col :span="8">
          <el-card class="preview-card">
            <template #header>
              <span>配置预览</span>
            </template>
            <ConfigPreview :config="configForm" />
          </el-card>

          <!-- 有效配置对比 -->
          <el-card v-if="isEdit" class="effective-config-card">
            <template #header>
              <span>有效配置</span>
              <el-button type="text" @click="loadEffectiveConfig">刷新</el-button>
            </template>
            <EffectiveConfigView
              v-if="effectiveConfig"
              :effective-config="effectiveConfig"
              :loading="loadingEffective" />
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAccountConfigStore } from '@/store/accountConfig'
import { ElMessage } from 'element-plus'
import { http } from '@/utils/request'
import TokenService from '@/utils/tokenService'
import CreateFromGlobalDialog from '@/components/CreateFromGlobalDialog.vue'
import ProxyConfigEditor from '@/components/ProxyConfigEditor.vue'
import JsonEditor from '@/components/JsonEditor.vue'
import ConfigPreview from '@/components/ConfigPreview.vue'
import EffectiveConfigView from '@/components/EffectiveConfigView.vue'

const route = useRoute()
const router = useRouter()
const accountConfigStore = useAccountConfigStore()

// 路由参数
const accountId = ref(parseInt(route.params.accountId))
const configId = ref(route.params.configId ? parseInt(route.params.configId) : null)
const isEdit = computed(() => !!configId.value)

// 表单引用
const configFormRef = ref()

// 状态
const saving = ref(false)
const loadingEffective = ref(false)
const fetchingTokenInfo = ref(false)
const accountName = ref('')
const effectiveConfig = ref(null)

// 配置表单
const configForm = reactive({
  configName: '',
  projectName: '',
  baseAsset: '',
  quoteAsset: 'USDT',
  chainId: 56,
  contractAddress: '',
  buyAmount: 0,
  targetBuyQuote: 0,
  proxyEnabled: false,
  proxyConfig: '',
  notifyUrl: '',
  customConfig: '{}',
  remark: ''
})

// 表单验证规则
const configRules = {
  configName: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
    { max: 100, message: '配置名称不能超过100个字符', trigger: 'blur' }
  ],
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { max: 100, message: '项目名称不能超过100个字符', trigger: 'blur' }
  ],
  baseAsset: [
    { required: true, message: '请输入基础资产代码', trigger: 'blur' },
    { max: 50, message: '基础资产代码不能超过50个字符', trigger: 'blur' }
  ],
  quoteAsset: [
    { required: true, message: '请输入报价资产代码', trigger: 'blur' },
    { max: 50, message: '报价资产代码不能超过50个字符', trigger: 'blur' }
  ],
  chainId: [
    { required: true, message: '请输入区块链ID', trigger: 'blur' },
    { type: 'number', min: 1, message: '区块链ID必须大于0', trigger: 'blur' }
  ],
  contractAddress: [
    { required: true, message: '请输入合约地址', trigger: 'blur' },
    { pattern: /^0x[a-fA-F0-9]{40}$/, message: '合约地址格式不正确', trigger: 'blur' }
  ]
}

// 初始化
onMounted(async () => {
  await loadAccountName()
  if (isEdit.value) {
    await loadConfigDetail()
    await loadEffectiveConfig()
  }
})

const loadAccountName = async () => {
  try {
    const response = await http.get(`/accounts/${accountId.value}`)
    accountName.value = response.data.name
  } catch (error) {
    accountName.value = `账号${accountId.value}`
  }
}

// 加载配置详情
const loadConfigDetail = async () => {
  try {
    const detail = await accountConfigStore.getAccountConfig(accountId.value, configId.value)

    // 填充表单
    Object.assign(configForm, {
      configName: detail.configName,
      projectName: detail.projectName,
      baseAsset: detail.baseAsset,
      quoteAsset: detail.quoteAsset,
      chainId: detail.chainId,
      contractAddress: detail.contractAddress,
      buyAmount: detail.buyAmount,
      targetBuyQuote: detail.targetBuyQuote,
      proxyEnabled: detail.proxyEnabled,
      proxyConfig: detail.proxyConfig || '',
      notifyUrl: detail.notifyUrl || '',
      customConfig: detail.customConfig || '{}',
      remark: detail.remark || ''
    })
  } catch (error) {
    ElMessage.error('加载配置详情失败')
    router.back()
  }
}

// 加载有效配置
const loadEffectiveConfig = async () => {
  loadingEffective.value = true
  try {
    effectiveConfig.value = await accountConfigStore.getEffectiveConfig(accountId.value)
  } catch (error) {
    console.warn('加载有效配置失败:', error)
  } finally {
    loadingEffective.value = false
  }
}

// 保存配置
const handleSave = async () => {
  if (!configFormRef.value) return

  try {
    await configFormRef.value.validate()
    saving.value = true

    if (isEdit.value) {
      await accountConfigStore.updateAccountConfig(accountId.value, configId.value, configForm)
    } else {
      await accountConfigStore.createAccountConfig(accountId.value, configForm)
    }

    router.back()
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    saving.value = false
  }
}

// 获取代币信息
const fetchTokenInfo = async () => {
  if (!configForm.contractAddress) {
    ElMessage.warning('请先输入合约地址')
    return
  }

  fetchingTokenInfo.value = true
  try {
    const tokenInfo = await TokenService.getTokenInfo(configForm.contractAddress, configForm.chainId)

    // 自动填充表单字段
    configForm.baseAsset = TokenService.generateBaseAsset(tokenInfo)
    configForm.projectName = tokenInfo.name

    // 使用symbol作为配置名称
    if (!configForm.configName) {
      configForm.configName = tokenInfo.symbol
    }

    ElMessage.success('代币信息获取成功')

    // 可选：显示详细信息
    console.log('获取到的代币信息:', tokenInfo)

  } catch (error) {
    ElMessage.error(error.message || '获取代币信息失败')
  } finally {
    fetchingTokenInfo.value = false
  }
}

// 处理合约地址输入变化
const handleContractAddressChange = () => {
  // 可以在这里添加额外的逻辑，比如清除之前的自动填充内容
  // 或者实时验证地址格式等
}

// 取消编辑
const handleCancel = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.account-config-edit {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .header-left {
      h3 {
        margin: 0 0 5px;
        color: #303133;
        font-size: 18px;
        font-weight: 600;
      }

      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .edit-content {
    .form-card {
      margin-bottom: 20px;

      .form-section {
        margin-bottom: 30px;

        h4 {
          margin: 0 0 15px;
          padding-bottom: 10px;
          color: #303133;
          font-size: 16px;
          font-weight: 600;
          border-bottom: 1px solid #ebeef5;
        }
      }

      .input-with-button {
        display: flex;
        gap: 8px;
        align-items: stretch;

        .el-input {
          flex: 1;
        }

        .fetch-button {
          flex-shrink: 0;
          white-space: nowrap;
        }
      }
    }

    .preview-card,
    .effective-config-card {
      margin-bottom: 20px;
    }
  }
}
</style>
